package T9_producer_consumer_2;

public class T9_produce_c{    
    public static void main(String[] args) {    
        Godown godown = new Godown(0);    
        Consumer c1 = new Consumer(500, godown);    
        Consumer c2 = new Consumer(20, godown);    
        Consumer c3 = new Consumer(30, godown);  
        Consumer c4 = new Consumer(5, godown);
        Producer p1 = new Producer(10, godown);    
        c1.start();    
        c2.start();    
        c3.start();    
        c4.start();  
        p1.start();    
    }    
}    
class Godown {    
	public static final int max_size = 100; 
	public int curnum;    
//	private boolean flage = false;
	Godown() {}    
	Godown(int curnum) {    
		this.curnum = curnum;    
	}    
	public synchronized void produce(int neednum) {    
		if(curnum == max_size) {    
			System.out.println("仓库已满，暂时不能执行生产任务!");  
			try {    
				wait();    
			} catch (InterruptedException e) {    
				e.printStackTrace();    
			}    
		}else if(max_size-curnum>neednum){
			curnum = curnum + neednum;    
			System.out.println("已经生产了" + neednum + "个产品，现仓储量为" + curnum); 
		}else{
			curnum++;//
			System.out.println("已经生产了 1 "+ "个产品，现仓储量为" + curnum); 
		}
		notifyAll();  
	}    
	public synchronized void consume(int neednum) {    
		if(neednum>max_size){
			System.out.println("已经消费量超过最大库存量，最多只能消费100");    
			try {    
				wait();    
			} catch (InterruptedException e) {    
				e.printStackTrace();    
			}    
		}else if(curnum < neednum) {   
			System.out.println("已经消费量超过当前库存量，请稍后");    
			try {    
				wait();    
			} catch (InterruptedException e) {    
				e.printStackTrace();    
			}    
		}else if(curnum > neednum){
			curnum = curnum - neednum;    
			System.out.println("已经消费了" + neednum + "个产品，现仓储量为" + curnum);   
		}    
		notifyAll();    
	}    
}    
class Producer extends Thread {    
	private int neednum;                //生产产品的数量    
	private Godown godown;            //仓库    
	Producer(int neednum, Godown godown) {    
		this.neednum = neednum;    
		this.godown = godown;    
	}    
	public void run() {
		while(true){
			godown.produce(neednum);  
		}
	}
}    
class Consumer extends Thread {    
	private int neednum;                //生产产品的数量    
	private Godown godown;            //仓库    
	Consumer(int neednum, Godown godown) {    
		this.neednum = neednum;    
		this.godown = godown;    
	}    
	public void run() {    
		godown.consume(neednum);    
	}    
}  
